package cn.jia.hrm.exception;

import cn.jia.hrm.AjaxResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
public class GlobleExceptionHandler {
    @ExceptionHandler(value = GlobalException.class)
    public AjaxResult ExceptionHandler(GlobalException e){
        return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
    }
    @ExceptionHandler(value = Exception.class)
    public AjaxResult ExceptionHandler1(GlobalException e){
        e.printStackTrace();
        return AjaxResult.me().setMessage("失败");
    }
    //异常处理 , ExceptionHandler 的作用是捕获异常，通过value指定要捕获的异常
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public AjaxResult ValidExceptionHandler(MethodArgumentNotValidException e){
        e.printStackTrace();   //这里面装的是错误的信息
        StringBuilder  sb = new StringBuilder();
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        allErrors.forEach(err->{  //循环遍历错误
            String defaultMessage = err.getDefaultMessage();
            sb.append(defaultMessage).append(" ; "); //拼接错误
        });
        return AjaxResult.me().setSuccess(false).setMessage(sb.toString());
    }

}
